package cn.wlinker.video.monitor.controller;

import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 自定义错误处理
 *
 * @author gxsjx
 * @version 1.0
 * @date 2025/5/3
 */
@RestController
public class CustomErrorController implements ErrorController {

    private static final String PATH = "/error";

    @RequestMapping(value = PATH)
    public ResponseEntity<Map<String, Object>> handleError(HttpServletRequest request) {
        // 获取HTTP状态码
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        // 从请求属性中提取异常
        Throwable e = (Throwable) request.getAttribute("javax.servlet.error.exception");
        // 处理 message
        String message = (e != null && e.getMessage() != null)
                ? e.getMessage()
                : "No error message available";
        // 创建自定义的JSON响应
        Map<String, Object> body = new HashMap<>(2);
        body.put("status", statusCode);
        body.put("message", message);
        // 返回自定义的JSON响应
        return new ResponseEntity<>(body, HttpStatus.valueOf(statusCode));
    }

    @Override
    public String getErrorPath() {
        return PATH;
    }
}